package com.ccy.product.web;

import com.ccy.product.entity.CategoryEntity;
import com.ccy.product.service.CategoryService;
import com.ccy.product.vo.Catalog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Slf4j
@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model){

        // TODO 1. 查出所有的1级分类
        List<CategoryEntity> level1Categories = categoryService.getLevel1Categories();
        model.addAttribute("categories", level1Categories);
        // 视图解析器进行拼串
        // classpath:/templates/.html
        return "index";
    }

    @ResponseBody
    @GetMapping("index/catalog.json")
    public Map<String, List<Catalog2Vo>> getCatalogJson(){
        return categoryService.getCatalogJson();
    }

    @GetMapping("/get")
    String testRedissonCountDownLatch() {
        RCountDownLatch countDownLatch = redissonClient.getCountDownLatch("count-down-lock");
        countDownLatch.trySetCount(5); //设置计数器
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "所有班级门都关了,开始放假...";
    }

    @GetMapping("/close")
    public String closeDoor() {
        RCountDownLatch countDownLatch = redissonClient.getCountDownLatch("count-down-lock");
        countDownLatch.countDown();
        return Thread.currentThread().getName() + "已关门";
    }

    @GetMapping("/park")
    String testRedissonSemaphore() {
        RSemaphore semaphore = redissonClient.getSemaphore("semaphore-lock");
        boolean result = semaphore.tryAcquire();
        if (!result){
            return "车位已满,请稍后再来...";
        }
        return "停车成功...";
    }

    @GetMapping("/out")
    String testRedissonSemaphoreOut() {
        RSemaphore semaphore = redissonClient.getSemaphore("semaphore-lock");
        semaphore.release();
        return "出场成功...";
    }
}
